#pragma once
#include <vector>
#include "mysql.hpp"
#include "logger.hpp"
#include "session_member.hxx"
#include "session_member-odb.hxx"

namespace zzy_mims
{
    class SessionMemberTable
    {
    public:
        using ptr = std::shared_ptr<SessionMemberTable>;
        SessionMemberTable(const std::shared_ptr<odb::core::database>& db):_db(db){};
        bool insert(SessionMember& sm)
        {
            try
            {
                odb::transaction trans(_db->begin());
                _db->persist(sm);
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("新增单成员会话失败{}-{}:{}",sm.user_id(),sm.session_id(),e.what());
                return false;
            }
            return true;
        }
        bool insert(std::vector<SessionMember>& sm_list)
        {
            try
            {
                odb::transaction trans(_db->begin());
                for(auto &sm:sm_list)
                _db->persist(sm);
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("新增多成员会话失败,size:{}:{}",sm_list.size(),e.what());
                return false;
            }
            return true;
        }
        bool remove(SessionMember& sm)
        {
            try
            {
                odb::transaction trans(_db->begin());
                _db->erase_query<SessionMember>(odb::query<SessionMember>::session_id==sm.session_id()
                &&odb::query<SessionMember>::user_id==sm.user_id());
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("删除单成员会话失败{}-{}:{}",sm.user_id(),sm.session_id(),e.what());
                return false;
            }
            return true;
        }
        bool remove(std::string& sid)
        {
            try
            {
                odb::transaction trans(_db->begin());
                _db->erase_query<SessionMember>(odb::query<SessionMember>::session_id==sid);
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("删除多成员会话失败,sid:{}:{}",sid,e.what());
                return false;
            }
            return true;
        }
        std::vector<std::string> members(const std::string& sid)
        {
            std::vector<std::string> user_list;
            try
            {
                odb::transaction trans(_db->begin());
                odb::result<SessionMember> r(_db->query<SessionMember>(odb::query<SessionMember>::session_id==sid));
                for(auto &e:r)
                user_list.emplace_back(e.user_id());
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("获取会话成员失败,sid:{}:{}",sid,e.what());
            }
            return user_list;
        }


    private:
        std::shared_ptr<odb::core::database> _db;
    };
}